<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="活动标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入活动标题"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属商家" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入所属的商家名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="活动状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in activityStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动类型" prop="actityType">
        <el-select
          v-model="queryParams.actityType"
          placeholder="活动类型"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in activityType"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="rolesKey == '00'"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openMerchant"
          v-hasPermi="['shop:activity:add']"
        >新增
        </el-button>
        <el-button
          v-else
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:activity:add']"
        >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <!--        <el-button-->
        <!--          type="danger"-->
        <!--          plain-->
        <!--          icon="el-icon-delete"-->
        <!--          size="mini"-->
        <!--          :disabled="multiple"-->
        <!--          @click="handleDelete"-->
        <!--          v-hasPermi="['system:role:remove']"-->
        <!--        >删除-->
        <!--        </el-button>-->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['shop:activity:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="活动主图"
                       align="center"
                       key="imgUrl"
                       width="150"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-image :src="scope.row.imgUrl"
                    style="width: 100px; height: 100px"
                    fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="活动标题" align="center" prop="title"/>
      <!-- <el-table-column label="创建者" align="center" prop="createBy" /> -->
      <el-table-column label="活动类型" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.actityType == 0">扫码领券</span>
          <span v-if="scope.row.actityType == 1">纯推广</span>
          <span v-if="scope.row.actityType == 2">抽奖</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="转发渠道" align="center" >
        <template slot-scope="scope">
          <span v-if="scope.row.forwardChannel == 0">抖音</span>
          <span v-if="scope.row.forwardChannel == 1">快手</span>
          <span v-if="scope.row.forwardChannel == 2">视频号</span>
          <span v-if="scope.row.forwardChannel == 3">微信朋友圈</span>
        </template>
      </el-table-column> -->


      <el-table-column label="所属商家" align="center" prop="shopName"/>
      <el-table-column label="活动描述" align="center" prop="description" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="小程序标题" align="center" prop="miniAppTitle" />
            <el-table-column label="延迟发送视频" prop="laterSend" >
              <template slot-scope="scope">
                <span>{{scope.row.joinCount == 0 ? '不延迟' : scope.row.joinCount + '小时'}}</span>

        </template>
      </el-table-column>

      <el-table-column label="每个人可参与次数" align="center" prop="joinCount">
        <template slot-scope="scope">
          <span>{{scope.row.joinCount == 0 ? '无限' : scope.row.joinCount}}</span>

        </template>

      </el-table-column> -->

      <el-table-column label="活动状态" align="center">
        <template slot-scope="scope">
          <!-- <span v-if="scope.row.status == 0">待审核</span> -->
          <span v-if="scope.row.status == 1">待上线</span>
          <span v-if="scope.row.status == 2">上线中</span>
          <span v-if="scope.row.status == 3">已下线</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否需要用户关注" align="center" >
        <template slot-scope="scope">
          <span v-if="scope.row.isFocus == 0">否</span>
          <span v-if="scope.row.isFocus == 1">是</span>
        </template>
      </el-table-column>

      <el-table-column label="地理位置名称" align="center" prop="poiName" />
      <el-table-column label="参与后跳转类型" align="center"  >
        <template slot-scope="scope">
          <span v-if="scope.row.redirectType == 0">优惠券页面</span>
          <span v-if="scope.row.redirectType == 1">商家抖音主页</span>
        </template>
      </el-table-column> -->

      <el-table-column label="活动周期" align="center">
        <template slot-scope="scope">
          <div>{{ parseTime(scope.row.beginDate) }}</div>
          至
          <div>{{ parseTime(scope.row.endDate) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="视频来源" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.videoSource == 0 ? '系统混剪' : '自定义单个视频'}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="视频标题" align="center" prop="videoTitle" />
      <el-table-column label="活动宣传视频" align="center" prop="videoUrl" width="200px" >
        <template slot-scope="scope">
          <a :href="scope.row.videoUrl" style="color:#00afff;" target="_blank">{{scope.row.videoUrl}}</a>
        </template>
      </el-table-column>
      <el-table-column label="按资源分组" align="center"  >
        <template slot-scope="scope">
          <span v-if="scope.row.videoSource == 0">按资源分组</span>
          <span v-if="scope.row.videoSource == 1">按单个文件</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="200" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:activity:edit']"
          >修改
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="activityCode(scope.row)"
          >查看活动二维码
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-copy-document"
            @click="copyCode(scope.row)"
          >复制活动地址
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleRouter('/coupon/coupon/list')"
          >优惠券
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleRouter('/resource/resource/class')"
          >资源视频分组
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--    商户列表-->
    <el-dialog title="选择商户" :visible.sync="merchantOpen" width="1400px" append-to-body>
      <el-row>
        <el-col :span="24" :xs="24">
          <el-form :model="queryMerchant" ref="queryMerchantForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="商户名称">
              <el-input
                v-model="queryMerchant.name"
                placeholder="请输入商户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="商户手机号码" label-width="100px" prop="phone">
              <el-input
                v-model="queryMerchant.phone"
                placeholder="请输入商户手机号码"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="商户状态" prop="status">
              <el-select
                v-model="queryMerchant.status"
                placeholder="商户状态"
                clearable
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="getMerchantList">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetMerchantQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="loading" :data="merchantList">
            <el-table-column label="商家头像" align="center" key="pic" width="150px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-image :src="scope.row.pic"
                          style="width: 100px; height: 100px"
                          fit="cover"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="商家ID" align="center" key="id" prop="id" :show-overflow-tooltip="true"/>
            <el-table-column label="商家名称" align="center" key="name" prop="name" :show-overflow-tooltip="true"/>
            <el-table-column label="负责人" align="center" key="leader	" prop="leader" :show-overflow-tooltip="true"/>
            <el-table-column label="代理商名称	" align="center" key="proxyName" prop="proxyName"/>
            <el-table-column label="代理商手机号码	" align="center" key="phone" prop="phone"/>
            <el-table-column label="营业时间" align="center" key="businessTime" prop="businessTime"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="商户邮箱" align="center" key="email" prop="email" :show-overflow-tooltip="true"/>
            <el-table-column label="热度" align="center" key="heat" prop="heat" :show-overflow-tooltip="true"/>
            <el-table-column label="商户余额	" align="center" key="videoCount" prop="videoCount"/>
            <el-table-column label="商户状态" align="center" key="status">
              <template slot-scope="scope">
                <span style="color: #3894ff" v-if="scope.row.status == 0">正常</span>
                <span style="color: #ed5565" v-if="scope.row.status == 1">停用</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="100px"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-add"
                  @click="handleAdd(scope.row)"
                  v-hasPermi="['system:user:edit']"
                >添加活动
                </el-button>
              </template>

            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryMerchant.pageNum"
            :limit.sync="queryMerchant.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 添加或修改活动配置对话框 -->
    <el-dialog class="stepBox" :title="title" :visible.sync="open" width="70%" @close="cancel" append-to-body>
      <el-steps :active="index" simple finish-status="success">
        <el-step title="优惠券和活动基本设置"></el-step>
        <el-step title="活动描述内容信息"></el-step>
        <el-step title="抖音视频发送信息"></el-step>
        <!-- <el-step title="步骤四"></el-step> -->
      </el-steps>
      <br>
      <el-form class="activity" ref="form" :model="form" :rules="rules" label-width="120px" size="small">
        <template v-if="index==0">
          <el-row>
            <el-col :span="8">
              <el-form-item key="form.actityType" label="活动类型" prop="actityType">
                <el-radio-group v-model="form.actityType">
                  <el-radio v-for="dict in activitysType"
                            :key="dict.dictValue"
                            :label="dict.dictValue"
                            :disabled="dict.disabled"
                  >{{dict.dictLabel}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" v-if="form.actityType != 1">
              <el-form-item key="form.couponIds" label="优惠券" prop="couponIds">
                <el-select v-model="form.couponIds" multiple placeholder="请选择优惠券" size="medium">
                  <el-option
                    v-for="dict in couponList"
                    :key="dict.id"
                    :label="dict.title"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" v-if="form.actityType != 1">
              <el-form-item key="form.isSynchronizationCoupon"  label="同步有效期" prop="isSynchronizationCoupon" size="small">
                <el-tooltip effect="light" content="将优惠券的有效期与活动周期同步" placement="top">
                  <div class="el-icon-question" style="margin-right:12px"></div>
                </el-tooltip>
                <el-radio-group v-model="form.isSynchronizationCoupon">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>

                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item key="form.joinCount" label="活动参与次数" prop="joinCount">
                <el-input-number v-model="form.joinCount" controls-position="right" :min="1"
                                 :max="1000"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item key="form.redirectType" label="参与后跳转类型" prop="redirectType">
                <el-tooltip effect="light" content="用户打开抖音扫码后" placement="top">
                  <div class="el-icon-question" style="margin-right:12px"></div>
                </el-tooltip>
                <el-select v-model="form.redirectType">
                  <el-option
                    v-for="dict in redirectTypes"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item key="form.status" label="活动状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio v-for="dict in activityStatus"
                            :key="dict.dictValue"
                            :label="dict.dictValue"
                  >{{dict.dictLabel}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item key="form.timeValue" label="活动有效范围">
                <el-date-picker
                  v-model="timeValue"
                  type="datetimerange"
                  :picker-options="pickerOptions"
                  range-separator="至"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="pickerChange"
                  align="right">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <template v-if="index == 1">
          <el-row>
            <el-col :span="8">
              <el-form-item key="form.imgUrl" label="活动主图">
                <upload v-model="form.imgUrl" :limit="1" @uploadSuccess="uploadSuccess"></upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item key="form.title" label="活动标题" prop="title" size="small">
                <el-input v-model="form.title"/>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item key="form.description" label="活动描述">
                <el-input type="textarea" v-model="form.description"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="24">
              <el-form-item key="form.context" label="活动内容" prop="context">
                <editor v-model="form.context" :min-height="192"/>
              </el-form-item>
            </el-col>
          </el-row>

        </template>
        <template v-if="index==2">
          <el-row>
            <el-col>
              <el-form-item key="form.isDoc" label="是否使用文案库">
                <el-switch
                  v-model="form.isDoc"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="使用"
                  inactive-text="不使用"
                  @change="changeSwitch($event)">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" class="videoTitle">
              <template v-if="form.isDoc == 0">
                <el-form-item key="form.videoTitle" label="抖音标题" prop="videoTitle">
                  <el-input maxlength="40"
                            show-word-limit
                            v-model="form.videoTitle"/>
                </el-form-item>
              </template>

            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" class="douyinTitles">
              <el-form-item key="form.douyinTitle" label="抖音话题" prop="douyinTitle">
                <el-tooltip content="请严格按照抖音要求完成话题，不然视频将无法发送" placement="top">
                  <div class="el-icon-warning"></div>
                </el-tooltip>
                <el-select
                  v-model="douyinTitles"
                  clearable
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="输入内容，用回车添加标签">
                  <el-option
                    v-for="(item,index) in douyinTitles"
                    :key="index"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item key="form.laterSend" label="延迟发送视频" prop="laterSend">
                <el-tooltip effect="light" content="单位：小时，系统在用户参与活动后会根据您设置的值发送视频，您也可以选择让用户参与后立即发送抖音视频" placement="top">
                  <div class="el-icon-question" style="margin-right:12px"></div>
                </el-tooltip>
                <el-input-number v-model="form.laterSend" placeholder="单位：小时" :disabled="laterSendFlag"
                                 controls-position="right" :min="0" :max="12" size="small"></el-input-number>

                <el-switch
                  v-model="form.laterSend"
                  :active-value="0"
                  :inactive-value="1"
                  active-text="立即发送"
                  style="margin-left: 30px"
                  @change="changeLaterSendInput($event)">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item key="form.tags" label="音乐标签" prop="tags">
                <el-tooltip effect="light" content="选择音乐标签，系统在视频加入背景音乐会从您的音乐资源里匹配相同标签进行混剪" placement="top">
                  <div class="el-icon-question" style="margin-right:12px"></div>
                </el-tooltip>
                <el-select v-model="form.tags"
                           multiple
                           placeholder="请选择">
                  <el-option
                    v-for="item in tagsOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="需要用户关注" prop="isFocus">
                <el-tooltip effect="light" content="开启后用户需要关注您的抖音账号才能参与活动" placement="top">
                  <div class="el-icon-question" style="margin-right:12px"></div>
                </el-tooltip>
                <el-switch
                  v-model="form.isFocus"
                  active-text="需要"
                  :active-value="1"
                  inactive-text="不需要"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="关联小程序">
                <el-tooltip effect="light" content="把自己的抖音小程序显示在用户抖音视频上，使用请在平台指导下使用" placement="top">
                  <div class="el-icon-question" style="margin-right:12px"></div>
                </el-tooltip>
                <el-switch
                  v-model="appletsSwitch"
                  active-text="开启"
                  inactive-text="关闭">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <template v-if="appletsSwitch">
              <el-col :span="8">
                <el-form-item label="小程序id" prop="miniAppId">
                  <el-input v-model="form.miniAppId"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="小程序标题" prop="miniAppTitle">
                  <el-input v-model="form.miniAppTitle"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="小程序url参数" prop="miniAppUrl">
                  <el-input v-model="form.miniAppUrl"/>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="显示店铺">
                <el-tooltip effect="light" content="把自己店铺的地理位置显示在用户抖音视频上" placement="top">
                  <div class="el-icon-question" style="margin-right:12px"></div>
                </el-tooltip>
                <el-switch
                  v-model="positionSwitch"
                  active-text="显示"
                  inactive-text="不显示">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
              <template v-if="positionSwitch">
                <el-col :span="8">
                  <el-form-item label=" 位置名称" prop="poiName">
                    <!-- <el-input v-model="form.poiName"/> -->
                    <el-select
                      v-model="form.poiName"
                      filterable
                      remote
                      reserve-keyword
                      width="100%"
                      placeholder="请输入您店铺地址位置"
                      @change="changePoi"
                      :remote-method="remoteMethod"
                      :loading="loading"
                    >
                      <el-option
                        v-for="item in poiList"
                        :key="item.id"
                        :value="item.poiName"
                        :label="item.poiName"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <!--  --------------此input框未来可能用到请不要删除此注视-------------------------->

                <!--              <el-col :span="8" v-if="false">-->
                <!--                <el-form-item label="地理位置id	" prop="poiId">-->
                <!--                  <el-input :disabled="true" v-model="form.poiId	"/>-->
                <!--                </el-form-item>-->
                <!--              </el-col>-->
              </template>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="视频素材来源" prop="redirectType">
                <el-tooltip effect="light" content="配置抖音视频的内容来源，您可以选择让系统自动选择视频内容混剪，也可以自定义视频内容" placement="top">
                  <div class="el-icon-question" style="margin-right:12px"></div>
                </el-tooltip>
                <el-radio-group v-model="form.videoSource">
                  <el-radio v-for="dict in videoSource"
                            :key="dict.dictValue"
                            :label="dict.dictValue"
                  >{{dict.dictLabel}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <template v-if="form.videoSource == 0">
              <el-col :span="8">
                <el-form-item label="资源混剪方式" prop="isRandFrag">
                  <el-tooltip effect="light" content="配置系统混剪视频资源属性" placement="top">
                    <div class="el-icon-question" style="margin-right:12px"></div>
                  </el-tooltip>
                  <el-radio-group v-model="form.isRandFrag">
                    <el-radio v-for="dict in isRandFrag"
                              :key="dict.dictValue"
                              :label="dict.dictValue"
                    >{{dict.dictLabel}}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="form.videoSource == 1">
              <el-form-item label="视频文件" prop="videoUrl">
                <file-upload v-model="form.videoUrl" @delUrl="delFileUrl" :fileType="['mp4']" :limit="1"></file-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

      </el-form>
      <div class="bottomButton">
        <el-button round size="mini" v-if="index!=0" @click="previous">上一步</el-button>
        <el-button :disabled="exhibit" v-if="index != 2" type="primary" round size="mini" @click="next"
                  >下一步</el-button>
        <el-button :disabled="exhibit" type="primary" round size="mini" @click="submitForm">提 交</el-button>
      </div>
    </el-dialog>
    <!--    活动二维码-->
    <el-dialog title="请打开抖音扫码" :visible.sync="codeOpen" width="300px" append-to-body>
      <div class="lookCode">
        <div id="qrCode" ref="qrCodeDiv"></div>
        <el-button class="copyBtn" type="primary" @click.stop="downloadCode">下载二维码</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { downLoadExcel } from '@/utils/download'
import {
  list,
  getActivity,
  addActivity,
  editActivity,
  delActivity,
  exportActivity,
  getActivityQrcode,
  activityShopCoupons,
  getIsWriting
} from '@/api/coupon/activity'
import upload from '@/components/ImageUpload'
import { getAuthQrCodeUrl, listUser } from '@/api/merchant/merchant'
import { mapState } from 'vuex'
import QRCode from 'qrcodejs2'
import { getSelectTags } from '@/api/tag/tag'
import { getAddress } from '@/api/merchant/merchant'
import fileUpload from '@/components/FileUpload/index'
import { deleteFile } from '@/api/resource/resource'
import {resetForm} from '@/utils/ruoyi'

export default {
  name: 'shopActivity',
  components: { upload, fileUpload },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示新增修改活动弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      //详情接口弹窗
      infoOpen: false,
      //活动详情表格
      activityList: [],
      //地址列表
      poiList: [],
      //下一步按钮是否展示
      exhibit: false,
      //保存删除文件url地址
      deleteFileUrl: [],
      // // 数据范围选项
      dataScopeOptions: [
        {
          value: '1',
          label: '全部数据权限'
        },
        {
          value: '2',
          label: '自定数据权限'
        },
        {
          value: '3',
          label: '本部门数据权限'
        },
        {
          value: '4',
          label: '本部门及以下数据权限'
        },
        {
          value: '5',
          label: '仅本人数据权限'
        }
      ],
      //活动标题标签
      douyinTitles: [],
      pickerOptions: {
        shortcuts: [{
          text: '未来一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '未来一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '未来三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //活动状态
      activityStatus: [
        { dictValue: '1', dictLabel: '待上线' }, { dictValue: '2', dictLabel: '上线中' }, { dictValue: '3', dictLabel: '已下线' }
      ],
      //同步有效期状态
      isSynchronizationCoupon: [],

      //活动类型
      activityType: [],
      //有禁用选项的活动类型
      activitysType: [
        { dictValue: '0', dictLabel: '扫码领券' },
        { dictValue: '1', dictLabel: '纯推广' },
        { dictValue: '2', dictLabel: '抽奖', disabled: true }
      ],
      //参与活动后跳转类型
      redirectTypes: [
        { dictValue: '0', dictLabel: '优惠券页面' },
        { dictValue: '1', dictLabel: '商家抖音主页' }
      ],
      //优惠券活动转发渠道
      forwardChannel: [],
      //视频来源
      videoSource: [],
      //资源混剪方式类型
      isRandFrag: [
        { dictValue: 0, dictLabel: '碎片混剪' },
        { dictValue: 1, dictLabel: '随机视频' }
      ],
      //时间范围默认值
      timeValue: [],
      merchantOpen: false,
      //商户列表请求表单
      queryMerchant: {
        pageNum: 1,
        pageSize: 20
      },
      //是否显示小程序
      appletsSwitch: false,
      //是否显示位置
      positionSwitch: false,
      //文案开关
      documentSwitch: false,
      //商户列表数据
      merchantList: [],
      //商户列表总数
      merchantTotal: '',
      //二维码弹窗开关
      codeOpen: false,
      //二维码地址
      codeUrl: '',
      //商户优惠券列表
      couponList: [],
      //标签列表
      tagsOptions: [],
      //二维码名称
      codeName: '',
      // 表单校验
      rules: {
        title: [
          { required: true, message: '活动标题不能为空', trigger: ['blur','change'] }
        ],
        couponIds:[
          { required: true, message: '优惠券不能为空', trigger: 'blur' }

        ],
        context: [
          { required: true, message: '活动内容不能为空', trigger: ['blur','change']}
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        videoUrl: [
          { required: true, message: '单视频时此选项必填' }
        ],
        isRandFrag: [
          { required: true, message: '选系统混剪时，该选项必填' }
        ]
      },
      //步骤的激活序号
      index: 0,
      //视频发送延时输入框开启禁用标记
      laterSendFlag: false
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
      this.statusOptions.forEach(item => {
        item.dictValue = Number(item.dictValue)

      })
    })
    //活动状态
    this.getDicts('activity_status').then(response => {
      // this.activityStatus = response.data;
      this.activityStatus.forEach(item => {
        item.dictValue = Number(item.dictValue)
      })
    })
    //活动类型
    this.getDicts('activity_type').then(response => {
      this.activityType = response.data
    })
    //参与活动后跳转类型
    this.getDicts('activity_redirectType').then(response => {
      this.redirectType = response.data;
      this.redirectType.forEach(item => {
        item.dictValue = Number(item.dictValue)
      })
    })
    //优惠券活动转发渠道
    this.getDicts('activity_forwardChannel').then(response => {
      this.forwardChannel = response.data
      this.forwardChannel.forEach(item => {
        item.dictValue = Number(item.dictValue)
      })
    })
    //同步有效期状态
    this.getDicts('activity_isSynchronizationCoupon').then(response => {
      this.isSynchronizationCoupon = response.data
      this.isSynchronizationCoupon.forEach(item => {
        item.dictValue = Number(item.dictValue)
      })
    })
    //视频来源
    this.getDicts('activity_videoSource').then(response => {
      this.videoSource = response.data
      this.videoSource.forEach(item => {
        item.dictValue = Number(item.dictValue)
      })
    })
  },
  computed: {
    ...mapState({
      rolesKey: state => state.user.rolesKey
    })
  },
  methods: {
    /** 查询活动列表 */
    getList() {
      this.loading = true
      list(this.queryParams).then(
        response => {
          this.roleList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    //选中地址函数
    changePoi(e) {
      this.poiList.forEach((item) => {
        if (item.poiName == e) {
          let local = []
          //将经纬度转为数组
          local = item.location.split(',')
          this.form.poiName = item.province + item.city + item.district + item.address
          this.form.log = local[0]
          this.form.lat = local[1]
          this.form.poiId = item.poiId
        }
      })
    },
    //添加的抖音标题
    changeDouyin() {
      var douyinTitleStr = ''
      this.douyinTitles.forEach((item) => {
        douyinTitleStr = douyinTitleStr + '#' + item
      })
      console.log(this.douyinTitles)
      return douyinTitleStr
    },
    //地址资源分组列表
    getPoiList(address) {
      getAddress({
        address
      }).then((response) => {
        this.poiList = response.data
      })
    },
    //远程搜索方法
    remoteMethod(query) {
      getAddress({
        address: query
      }).then((res) => {
        this.poiList = res.data
      })
    },

    //查看活动二维码
    activityCode(row) {
      getActivityQrcode({
        activityId: row.id
      }).then(res => {
        this.$refs.qrCodeDiv.innerHTML = ''

        this.$nextTick(function() {
          this.bindQRCode(res.msg)
          this.codeName = row.shopName
        })
      })
      this.codeOpen = true
    },
    //复制活动二维码
    copyCode(row) {
      getActivityQrcode({
        activityId: row.id
      }).then(res => {
        this.$copyText(res.msg).then(e => {
          this.msgSuccess('复制成功')
        })

      })
    },
    //获取商户列表
    getMerchantList() {
      this.loading = true
      listUser(this.queryMerchant).then(response => {
          this.merchantList = response.rows
          this.merchantTotal = response.total
          this.loading = false
        }
      )
    },
    //二维码函数
    bindQRCode: function(url) {
      new QRCode(this.$refs.qrCodeDiv, {
        text: url,
        width: 200,
        render: 'canvas',
        height: 200,
        colorDark: '#333333', //二维码颜色
        colorLight: '#ffffff', //二维码背景色
        correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
      })
    },
    //下载二维码
    downloadCode(name) {
      var canvasData = this.$refs.qrCodeDiv.getElementsByTagName('canvas')
      var a = document.createElement('a')
      var event = new MouseEvent('click') // 创建一个单击事件
      a.href = canvasData[0].toDataURL('image/png')
      a.download = this.codeName + '二维码'
      a.dispatchEvent(event) // 触发a的单击事件
    },
    //获取商户优惠券列表
    getCouponList(id) {
      activityShopCoupons({
        shopId: id
      }).then(res => {
        this.couponList = res.data
      })
    },
    //是否使用文案提示
    changeSwitch(val){
     if(val === 1){
       getIsWriting({shopId: this.form.shopId}).then(res => {
        if(!res.data){
          this.$message({
          showClose: true,
          message: '你还没编写文案哦！！！',
          type: 'warning'
        });
        this.form.isDoc = 0
        }
      })     
     }else{}
    },
    //获取音乐标签
    getTags(id) {
      getSelectTags({
        shopId: id
      }).then(res => {
        this.tagsOptions = res.data
        // console.log('tag结果',this.tagsOptions)
      })
    },
    //路由跳转
    handleRouter(path) {
      this.$router.replace(path)
    },
    // 活动状态修改
    handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.roleName + '"活动吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeRoleStatus(row.roleId, row.status)
      }).then(() => {
        this.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    //日期选择器赋值
    pickerChange(e) {
      console.log(e)
      this.form.beginDate = e[0]
      this.form.endDate = e[1]
    },
    //获取删除url地址
    delFileUrl(url) {
      this.deleteFileUrl.push(url)

      this.form.videoUrl = ''
    },
    //删除文件
    delFile(url) {
      deleteFile(url).then(res => {
        this.deleteFileUrl.forEach((item, index) => {
          if (item == url) {
            this.deleteFileUrl.splice(index, 1)
          }
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;

      //如果在新增操作中上传了文件没有点保存点击了取消 删除刚刚上传的文件
      if (this.form.id == undefined && this.form.videoUrl){
        this.delFile(this.form.audioUrl);
      }
      //判断是否是新增资源操作 如果是将删除之前 删除文件(deleteFileUrl)列表中的资源
      if (this.deleteFileUrl.length > 0 && this.form.id == undefined){
        this.deleteFileUrl.forEach((item,index) =>{
          this.delFile(item);
        })
      }
      //在修改情况下，如果点击删除操作上传一个新文件但是点了取消操作 将删除新文件地址不删除原文件地址
      if(this.form.id && this.form.videoUrl){
        if (this.deleteFileUrl.length > 0){
          this.delFile(this.form.videoUrl);
        }
      }
      // 判断是否是修改资源操作
      if (this.deleteFileUrl.length > 0 && this.form.id != undefined){
        this.deleteFileUrl.forEach((item,index) =>{
          //如果是修改操作点击取消将不删除最后一条数据
          if (this.deleteFileUrl.length != index +1){
            this.delFile(item);
          }
        })
      }
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.$refs.form.resetFields();

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();

      this.handleQuery()
    },
    //上传封面
    uploadSuccess(url) {
      this.form.imgUrl = url
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      console.log(this.ids)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleDataScope':
          this.handleDataScope(row)
          break
        case 'handleAuthUser':
          this.handleAuthUser(row)
          break
        default:
          break
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false
      }
    },
    //打开商户列表
    openMerchant() {
      this.getMerchantList()
      this.merchantOpen = true
    },
    //重置商户传参数
    resetMerchantQuery() {
      this.resetForm('queryMerchantForm')
      this.getMerchantList()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.index = 0
      this.open = true;
      this.form = {}
      this.title = '添加活动'
      this.form.shopId = row.id
      this.getCouponList(row.id)
      this.getTags(row.id);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = {};
      this.index = 0
      const id = row.id || this.ids
      this.getCouponList(row.shopId)
      this.getTags(row.shopId)
      getActivity(id).then(response => {
        console.log(response.data.redirectType)
        this.form = response.data
        let douyinLabel = this.form.douyinTitle.split('#')
        douyinLabel.shift(0)
        this.form.douyinTitle = douyinLabel
        this.douyinTitles = douyinLabel
        this.timeValue = []
        this.timeValue.push(this.form.beginDate)
        this.timeValue.push(this.form.endDate)
        this.open = true
        this.title = '修改活动'
      })
    },

    /** 选择活动权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== '2') {
        this.$refs.dept.setCheckedKeys([])
      }
    },

    /** 分配用户操作 */
    handleAuthUser: function(row) {
      const roleId = row.roleId
      this.$router.push('/system/role-auth/user/' + roleId)
    },

    /** 步骤条上一步按钮 */
    previous(){
      this.index --;
      this.$refs['form'].clearValidate();
    },
    /** 步骤条下一步按钮 */
    next() {
      this.$refs['form'].validate(valid =>{
        if(valid){
          if (this.index  < 2) {
            this.index++
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {

          this.form.douyinTitle=this.changeDouyin();
          if (this.form.id != undefined) {
            editActivity(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addActivity(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false;
              this.merchantOpen = false;
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const couponId = row.id || this.ids.toString()
      this.$confirm('是否确认删除活动为"' + couponId + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delActivity(couponId)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      downLoadExcel('/shop/activity/export', this.queryParams)
    },


    //延时发送视频是否立即发送函数
    changeLaterSendInput(event) {
      if (event === 1) {
        this.laterSendFlag = false
      } else {
        this.laterSendFlag = true
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.lookCode {
  display: flex;
  flex-flow: column;
  align-items: center;

  .copyBtn {
    margin-top: 20px;
  }
}


.activity {
  min-height: 300px;
  max-height: 500px;
  overflow: auto;
}

.bottomButton {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

::v-deep .el-step__title.is-process {
  color: #1F3F66;
}
::v-deep .videoTitle .el-input{
  width: 60% !important;

}
::v-deep .douyinTitles .el-select{
  width: 60%;
  margin-left: 20px;
}
</style>
